"""
场景管理页面
"""
import streamlit as st
from models.scene import Scene
from core.scene_manager import SceneManager


def show():
    """
    显示场景管理页面
    """
    st.title("场景管理")
    
    # 初始化场景管理器
    scene_manager = SceneManager()
    
    # 场景操作选项卡
    tab1, tab2, tab3 = st.tabs(["创建场景", "编辑场景", "删除场景"])
    
    with tab1:
        # 创建新场景
        with st.form("create_scene_form"):
            name = st.text_input("场景名称*")
            description = st.text_area("场景描述")
            scene_type = st.selectbox(
                "场景类型*",
                options=["销售预测", "投资回报分析", "成本测算", "其他"]
            )
            
            submitted = st.form_submit_button("创建")
            if submitted:
                if not name:
                    st.error("请填写场景名称")
                else:
                    new_scene = Scene(name, description, scene_type)
                    scene_id = scene_manager.create_scene(new_scene)
                    st.success(f"场景 '{name}' 创建成功！ID: {scene_id}")
    
    with tab2:
        # 编辑现有场景
        scenes = scene_manager.list_scenes()
        if not scenes:
            st.info("暂无可用场景")
        else:
            selected_scene = st.selectbox(
                "选择要编辑的场景",
                options=[s.name for s in scenes],
                key="edit_scene_select"
            )
            
            scene_to_edit = next(s for s in scenes if s.name == selected_scene)
            
            with st.form("edit_scene_form"):
                new_name = st.text_input("新名称", value=scene_to_edit.name)
                new_description = st.text_area("新描述", value=scene_to_edit.description)
                
                submitted = st.form_submit_button("保存更改")
                if submitted:
                    scene_to_edit.name = new_name
                    scene_to_edit.description = new_description
                    scene_manager.update_scene(scene_to_edit)
                    st.success("场景更新成功！")
    
    with tab3:
        # 删除场景
        scenes = scene_manager.list_scenes()
        if not scenes:
            st.info("暂无可用场景")
        else:
            selected_scene = st.selectbox(
                "选择要删除的场景",
                options=[s.name for s in scenes],
                key="delete_scene_select"
            )
            
            if st.button("删除场景", key="delete_scene_btn"):
                scene_manager.delete_scene(selected_scene)
                st.success(f"场景 '{selected_scene}' 已删除")
    
    # 显示所有场景
    st.divider()
    st.subheader("所有场景")
    scenes = scene_manager.list_scenes()
    if not scenes:
        st.info("暂无场景")
    else:
        for scene in scenes:
            with st.expander(f"{scene.name} ({scene.scene_type})"):
                st.write(f"**ID:** {scene.id}")
                st.write(f"**描述:** {scene.description}")
                st.write(f"**创建时间:** {scene.created_at}")
                st.write(f"**最后修改:** {scene.updated_at}")